package com.three.iot.service.impl;

import com.three.iot.api.DataStoreService;
import com.three.iot.commons.utils.DateUtil;
import com.three.iot.jdbc.mapper.TCacheInfoMapper;
import com.three.iot.jdbc.model.TCacheInfo;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.TimeZone;

/**
 * @author luiz
 * @Title: TkCacheInfoServiceImpl
 * @ProjectName iot
 * @Description: TODO
 * @date 2019-04-03 18:41
 */
@Component
public class TCacheInfoServiceImpl implements DataStoreService {
    @Resource
    private TCacheInfoMapper tCacheInfoMapper;

    @Override
    public void put(String key, String objVal) {
        //默认30分钟
        put(key, objVal, 1800);
    }

    @Override
    public void put(String key, String objVal, int defaultSeconds) {
        TCacheInfo tkCacheInfo = new TCacheInfo();
        tkCacheInfo.setCacheKey(key);
        tkCacheInfo.setCacheVal(objVal);
        tkCacheInfo.setStartTime(new Date());
        Date endDate = DateUtil.addSeconds(new Date(), defaultSeconds);
        tkCacheInfo.setEndTime(endDate);
        TCacheInfo tkCacheInfoOld =tCacheInfoMapper.selctByIndex(key);
        if(tkCacheInfoOld==null){
            tCacheInfoMapper.insert(tkCacheInfo);
        }else {
            tkCacheInfo.setId(tkCacheInfoOld.getId());
            tkCacheInfo.setStartTime(null);
            tCacheInfoMapper.updateByPrimaryKeySelective(tkCacheInfo);
        }
    }

    @Override
    public String getVal(String cacheKey) {
        TCacheInfo tkCacheInfo = tCacheInfoMapper.selctByIndex(cacheKey);
        if (tkCacheInfo != null) {
            return tkCacheInfo.getCacheVal();
        }
        return null;
    }

    @Override
    public void del(String cacheKey) {
        tCacheInfoMapper.deleteByCacheKey(cacheKey);
    }


}
